<?php
require_once 'Models/Admin/Service/AdminBaseService.php';

class AdminUserService extends AdminBaseService {
	
	public function add(array $fields) {
		if (!is_array($fields) || !isset($fields['user_name']) || !isset($fields['password'])) return 0;
		if ('' == $fields['user_name'] || '' == $fields['password']) return 0;
		$fields['password'] = md5($fields['password']);
		return $this->getAdminUserDao()->add($fields);
	}
	
	public function update($userId, $fields) {
		if ($userId <= 0 || !is_array($fields) || !count($fields)) return 0;
		if (isset($fields['password'])) $fields['password'] = md5($fields['password']);
		return $this->getAdminUserDao()->update($userId, $fields);
	}
	
	public function get($userId) {
		if ($userId <= 0) return null;
		return $this->getAdminUserDao()->get($userId);
	}
	
	public function getByName($username) {
		$username = trim((string)$username);
		if ('' == $username) return null;
		return $this->getAdminUserDao()->getByName($username);
	}
	
	public function login($userName, $password, $loginIp = '') {
		if ('' == $userName || '' == $password) return false;
		$adminUser = $this->getAdminUserDao()->getByName($userName);
		if (!$adminUser || $adminUser['password'] != md5($password)) return false;
		
		unset($adminUser['password']);
		$this->update($adminUser['user_id'], array('last_login_ip' => $loginIp, 'last_login_time' => time()));
		return $adminUser;
	}
	
	public function isUserNameExist($userName) {
		if ('' == $userName) return false;
		$adminUser = $this->getAdminUserDao()->getByName($userName);
		return $adminUser ? true : false;
	}
	
	public function delete($userId) {
		if ($userId <= 0) return 0;
		return $this->getAdminUserDao()->delete($userId);
	}
	
	public function findAll() {
		return $this->getAdminUserDao()->findAll();
	}
	
	
	protected function getAdminUserDao() {
		require_once 'Models/Admin/Dao/AdminDaoFactory.php';
		return AdminDaoFactory::getInstance()->createAdminUserDao();
	}
}
